const Service = require("egg").Service;
const dayjs = require("dayjs");

// 请求打印数据
class PrintService extends Service {
	// 打印合同数据
	async getPrintContractData(contractId) {
		let { knex } = this.app;
		// 查询视图_view_car_contract_customer符合contractId的数据
		let result = await knex("_view_car_contract_customer").where({ contractId }).select().first();
		let { year: startYear, month: startMonth, day: startDay } = this.splitDate(result.contractStartTime);
		let { year: endYear, month: endMonth, day: endDay } = this.splitDate(result.contractEndTime);
		let totalMonth = this.getMonthDiff(result.contractStartTime, result.contractEndTime);
		let totalRentAmount = totalMonth == 0 ? result.rentAmount : result.rentAmount * totalMonth;
		return {
			contractId: result.contractId,
			customerName: result.customerName,
			startDay,
			startMonth,
			startYear,
			endYear,
			endDay,
			endMonth,
			totalMonth,
			nowYear: dayjs().year(),
			nowMonth: dayjs().month() + 1 > 10 ? dayjs().month() : "0" + dayjs().month(),
			nowDay: dayjs().day() > 10 ? dayjs().day() : "0" + dayjs().day(),
			totalRentAmount,
			// 暂定1辆
			carTotal: 1,
			carType: result.carType,
			carColor: result.carColor,
			carSeats: result.carSeats,
			carNumber: result.carNumber,
			rentAmount: result.rentAmount,
			depositAmount: result.depositAmount,
		};
	}
	// 计算合同总共多少个月
	getMonthDiff(startDate, endDate) {
		const start = dayjs(startDate, "YYYY-MM-DD");
		const end = dayjs(endDate, "YYYY-MM-DD");

		const diffMonths = end.diff(start, "month");
		const diffDays = end.diff(start.add(diffMonths, "month"), "day");

		if (diffDays > 0) {
			return diffMonths + 1;
		} else {
			return diffMonths;
		}
	}
	// 将日期分割成年月日返回
	splitDate(date) {
		let newDateArr = dayjs(date).format("YYYY-MM-DD").split("-");
		return {
			year: newDateArr[0],
			month: newDateArr[1],
			day: newDateArr[2],
		};
	}
}
module.exports = PrintService;
